{% extends 'base.html' %}

{% block title %}首页 - Neo4j图数据库管理系统{% endblock %}

{% block extra_css %}
<style>
    .editable-cell {
        padding: 5px;
        border: 1px solid transparent;
    }
    .editable-cell:hover {
        border: 1px solid #ddd;
    }
    .editable-cell:focus {
        outline: none;
        border: 1px solid #66afe9;
        box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
    }
    .relation-table {
        margin-top: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>节点搜索</h4>
            </div>
            <div class="card-body">
                <div class="input-group mb-3">
                    <input type="text" id="search-input" class="form-control" placeholder="输入搜索关键词..." aria-label="搜索关键词">
                    <button class="btn btn-primary" id="search-btn">搜索</button>
                </div>
                <div id="search-status" class="alert d-none" role="alert"></div>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>搜索结果</h4>
            </div>
            <div class="card-body">
                <div id="no-results" class="alert alert-info d-none" role="alert">
                    没有找到匹配的节点
                </div>
                <div id="results-container" class="d-none">
                    <h5>节点列表</h5>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="nodes-table">
                            <thead>
                                <tr>
                                    <th>节点ID</th>
                                    <th>标签</th>
                                    <th>属性</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="nodes-table-body"></tbody>
                        </table>
                    </div>

                    <div id="relations-section" class="d-none mt-5">
                        <h5>节点关系</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <h6>入边关系</h6>
                                <div class="table-responsive relation-table">
                                    <table class="table table-striped table-hover" id="incoming-relations-table">
                                        <thead>
                                            <tr>
                                                <th>源节点</th>
                                                <th>关系类型</th>
                                                <th>属性</th>
                                            </tr>
                                        </thead>
                                        <tbody id="incoming-relations-body"></tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>出边关系</h6>
                                <div class="table-responsive relation-table">
                                    <table class="table table-striped table-hover" id="outgoing-relations-table">
                                        <thead>
                                            <tr>
                                                <th>目标节点</th>
                                                <th>关系类型</th>
                                                <th>属性</th>
                                            </tr>
                                        </thead>
                                        <tbody id="outgoing-relations-body"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <button id="save-changes-btn" class="btn btn-success mt-3 d-none">保存修改</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 存储当前编辑的节点和修改
        let currentNodes = [];
        let modifiedNodes = new Map();
        let currentNodeId = null;

        // 搜索按钮点击事件
        $('#search-btn').click(function() {
            searchNodes();
        });

        // 回车键触发搜索
        $('#search-input').keypress(function(e) {
            if (e.which === 13) {
                searchNodes();
            }
        });

        // 保存修改按钮点击事件
        $('#save-changes-btn').click(function() {
            saveChanges();
        });

        // 搜索节点函数
        function searchNodes() {
            const searchString = $('#search-input').val().trim();
            if (!searchString) {
                showStatus('请输入搜索关键词', 'warning');
                return;
            }

            showStatus('搜索中...', 'info');
            $('#no-results').addClass('d-none');
            $('#results-container').addClass('d-none');
            $('#relations-section').addClass('d-none');
            $('#save-changes-btn').addClass('d-none');
            currentNodes = [];
            modifiedNodes.clear();
            currentNodeId = null;

            $.ajax({
                url: `/search?q=${encodeURIComponent(searchString)}`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.count === 0) {
                        $('#no-results').removeClass('d-none');
                        showStatus('没有找到匹配的节点', 'info');
                    } else {
                        currentNodes = response.nodes;
                        renderNodesTable(currentNodes);
                        $('#results-container').removeClass('d-none');
                        showStatus(`找到 ${response.count} 个匹配的节点`, 'success');
                    }
                },
                error: function(xhr, status, error) {
                    const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : `搜索失败: ${error}`;
                    showStatus(errorMsg, 'danger');
                }
            });
        }

        // 渲染节点表格
        function renderNodesTable(nodes) {
            const tableBody = $('#nodes-table-body');
            tableBody.empty();

            nodes.forEach(node => {
                const propertiesHtml = renderProperties(node.properties, node.id);
                const labelsHtml = node.labels.join(', ');
                const row = `
                    <tr data-node-id="${node.id}">
                        <td>${node.id}</td>
                        <td>${labelsHtml}</td>
                        <td>${propertiesHtml}</td>
                        <td>
                            <button class="btn btn-info btn-sm view-relations-btn" data-node-id="${node.id}">查看关系</button>
                        </td>
                    </tr>
                `;
                tableBody.append(row);
            });

            // 绑定查看关系按钮事件
            $('.view-relations-btn').click(function() {
                const nodeId = $(this).data('node-id');
                viewNodeRelations(nodeId);
            });

            // 绑定属性编辑事件
            $('.editable-cell').click(function() {
                const nodeId = $(this).data('node-id');
                const propName = $(this).data('prop-name');
                const currentValue = $(this).text();
                $(this).html(`<input type="text" value="${currentValue}" class="form-control prop-input" data-node-id="${nodeId}" data-prop-name="${propName}">`);
                $(this).find('input').focus();
            });

            // 绑定输入框失去焦点事件
            $(document).on('blur', '.prop-input', function() {
                const nodeId = $(this).data('node-id');
                const propName = $(this).data('prop-name');
                const newValue = $(this).val();
                const cell = $(this).parent();
                cell.text(newValue);

                // 更新修改记录
                if (!modifiedNodes.has(nodeId)) {
                    // 找到原始节点
                    const originalNode = currentNodes.find(n => n.id === nodeId);
                    if (originalNode) {
                        modifiedNodes.set(nodeId, { ...originalNode.properties });
                    }
                }

                // 更新属性值
                const nodeChanges = modifiedNodes.get(nodeId);
                nodeChanges[propName] = newValue;

                // 显示保存按钮
                $('#save-changes-btn').removeClass('d-none');
            });
        }

        // 渲染属性
        function renderProperties(properties, nodeId) {
            if (!properties || Object.keys(properties).length === 0) {
                return '无属性';
            }

            let html = '<ul class="list-unstyled">';
            for (const [key, value] of Object.entries(properties)) {
                html += `
                    <li><strong>${key}:</strong> <span class="editable-cell" data-node-id="${nodeId}" data-prop-name="${key}">${value}</span></li>
                `;
            }
            html += '</ul>';
            return html;
        }

        // 查看节点关系
        function viewNodeRelations(nodeId) {
            currentNodeId = nodeId;
            showStatus('加载节点关系中...', 'info');

            $.ajax({
                url: `/node/${nodeId}`,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    renderRelationsTables(response);
                    $('#relations-section').removeClass('d-none');
                    showStatus('节点关系加载成功', 'success');
                },
                error: function(xhr, status, error) {
                    const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : `加载节点关系失败: ${error}`;
                    showStatus(errorMsg, 'danger');
                }
            });
        }

        // 渲染关系表格
        function renderRelationsTables(nodeData) {
            // 渲染入边关系
            const incomingBody = $('#incoming-relations-body');
            incomingBody.empty();

            nodeData.incoming_relations.forEach(relation => {
                const sourceNode = relation.source;
                const sourceLabels = sourceNode.labels.join(', ');
                const propertiesHtml = renderRelationProperties(relation.properties);
                const row = `
                    <tr>
                        <td>${sourceNode.id}<br><small>${sourceLabels}</small></td>
                        <td>${relation.type}</td>
                        <td>${propertiesHtml}</td>
                    </tr>
                `;
                incomingBody.append(row);
            });

            // 渲染出边关系
            const outgoingBody = $('#outgoing-relations-body');
            outgoingBody.empty();

            nodeData.outgoing_relations.forEach(relation => {
                const targetNode = relation.target;
                const targetLabels = targetNode.labels.join(', ');
                const propertiesHtml = renderRelationProperties(relation.properties);
                const row = `
                    <tr>
                        <td>${targetNode.id}<br><small>${targetLabels}</small></td>
                        <td>${relation.type}</td>
                        <td>${propertiesHtml}</td>
                    </tr>
                `;
                outgoingBody.append(row);
            });
        }

        // 渲染关系属性
        function renderRelationProperties(properties) {
            if (!properties || Object.keys(properties).length === 0) {
                return '无属性';
            }

            let html = '<ul class="list-unstyled">';
            for (const [key, value] of Object.entries(properties)) {
                html += `<li><strong>${key}:</strong> ${value}</li>`;
            }
            html += '</ul>';
            return html;
        }

        // 保存修改
        function saveChanges() {
            if (modifiedNodes.size === 0) {
                showStatus('没有需要保存的修改', 'info');
                return;
            }

            showStatus('保存修改中...', 'info');
            let saveCount = 0;
            let errorCount = 0;

            modifiedNodes.forEach((properties, nodeId) => {
                $.ajax({
                    url: `/node/${nodeId}`,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        node_id: nodeId,
                        properties: properties
                    }),
                    success: function(response) {
                        saveCount++;
                        if (saveCount + errorCount === modifiedNodes.size) {
                            finishSave(saveCount, errorCount);
                        }
                    },
                    error: function(xhr, status, error) {
                        errorCount++;
                        if (saveCount + errorCount === modifiedNodes.size) {
                            finishSave(saveCount, errorCount);
                        }
                    }
                });
            });
        }

        // 完成保存
        function finishSave(saveCount, errorCount) {
            if (errorCount === 0) {
                showStatus(`成功保存 ${saveCount} 个节点的修改`, 'success');
            } else {
                showStatus(`成功保存 ${saveCount} 个节点，${errorCount} 个节点保存失败`, 'warning');
            }

            // 清除修改记录
            modifiedNodes.clear();
            $('#save-changes-btn').addClass('d-none');
        }

        // 显示状态消息
        function showStatus(message, type) {
            const statusEl = $('#search-status');
            statusEl.text(message);
            statusEl.removeClass('d-none alert-info alert-success alert-warning alert-danger');
            statusEl.addClass(`alert-${type}`);

            // 5秒后自动隐藏非错误消息
            if (type !== 'danger') {
                setTimeout(() => {
                    statusEl.addClass('d-none');
                }, 5000);
            }
        }
    });
</script>
{% endblock %}